package com.gitee.wsl.compose.ui.container.swipe

import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import com.gitee.wsl.compose.ui.base.Layout
import kotlinx.coroutines.delay


@Composable
fun <T> Layout.SwipeToDeleteContainer(
  item: T,
  onDelete: () -> Unit,
  modifier: Modifier = Modifier,
  animationDuration: Int = 300,
  content: @Composable (T) -> Unit
) {
  var isRemoved by remember { mutableStateOf(false) }
  val state = rememberSwipeToDismissBoxState(
    confirmValueChange = {
      if (it == SwipeToDismissBoxValue.EndToStart) {
        isRemoved = true
        true
      } else false
    }
  )
  
  LaunchedEffect(isRemoved) {
    if (isRemoved) {
      delay(animationDuration.toLong())
      onDelete()
      isRemoved = false
    }
  }
  
  if (!isRemoved) {
    SwipeToDismissBox(
      state = state,
      backgroundContent = { DeleteBackground(state) },
      //directions = setOf(DismissDirection.EndToStart),
      enableDismissFromStartToEnd = false,
      modifier = modifier
    ){
      content(item)
    }
  }
}